package main;

import java.io.IOException;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.DriverManager;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class general {
	// Method to read URL. Returns as a string.
	public String readUrl(String urlString) throws Exception {
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(urlString);
		HttpResponse response = httpclient.execute(httpget);
		HttpEntity entity = response.getEntity();
		
		if (response.getStatusLine().getStatusCode() == 429) {
			return "429";
		}
		
		String entityContents = null;
		if (entity != null) {
			entityContents = EntityUtils.toString(entity);
		}
		return entityContents;
	}
	
	public Connection getmySQLConnection() {
		try {
			//Create a new instance for the connector
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			//Set up the connection with the correct information
			Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/erepbot?user=root&password=erepbot");
			//Return the connection
			return con;
		} catch (Exception e) {
			// If there is an error, print the error and return a null value
			System.out.println("Exception: " + e.getMessage());
			return null;
		}
	}
	
	public String getJSON(String resource, String action,Map<String, String> query) {
		String url = "http://api.erepublik.com/"+resource+"/"+action+"?";
		String data = resource+":"+action+":";
		for (Entry<String, String> entry : query.entrySet()) {
		    url = url + entry.getKey() + "=" + entry.getValue() + "&";
		    data = data + entry.getKey() + "=" + entry.getValue() + "&";
		}
		url = url.substring(0, url.length() - 1);
		data = data.substring(0, data.length() - 1) + ":";			
		
		String jsonString = null;
		try {
			jsonString = readAPI(url, data);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonString;
	}

	private static String getHMAC(String privKey,String digest) {
		String hmac = "";
		try {
	        Mac mac = Mac.getInstance("HmacSHA256");
	        SecretKeySpec secret = new SecretKeySpec(privKey.getBytes(),"HmacSHA256");
	        mac.init(secret);
	        byte[] digestB = mac.doFinal(digest.getBytes());
	        BigInteger hash = new BigInteger(1, digestB);
	        hmac = hash.toString(16);

	        if (hmac.length() % 2 != 0) {
	            hmac = "0" + hmac;
	        }
	    } catch (Exception e) {
	        System.out.println(e.getMessage());
	    }
		return hmac;
	}
	
	private static String readAPI(String urlString, String data) throws ClientProtocolException, IOException {
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(urlString);
		
		String privKey = "02b1ba2959281537367d26b04a5c55";
		String pubKey = "2633654abff7";

		Date dNow = new Date( );
	    SimpleDateFormat ft = new SimpleDateFormat ("dd-MM-Y HH:mm:ss Z");
	    String date = ft.format(dNow);
	    
	    String digest = getHMAC(privKey,data+date);
	    
		httpget.setHeader("Auth", pubKey+"/"+digest);
		httpget.setHeader("Date", date);
		HttpResponse response = httpclient.execute(httpget);
		HttpEntity entity = response.getEntity();
		
		String entityContents = null;
		if (entity != null) {
			entityContents = EntityUtils.toString(entity);
		}
		return entityContents;
	}
}
